package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.dao.EventMsgDao;
import cc.linker.steplink.crm.dao.LabelDao;
import cc.linker.steplink.crm.domain.Customer;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.WxShareService;
import com.mongodb.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 扫描带参数的二维码后保存用户链路关系
 */

@Component
public class WxShareTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LabelDao labelDao;
    @Autowired
    private EventMsgDao eventMsgDao;
    @Autowired
    private MallBoomService mallBoomService;
    @Autowired
    private WxShareService wxShareService;

    @Async
    @RedisLock(value = "wxShareTask")
    @Scheduled(cron = "0 0/1 * * * ?")
    public void wxShareSaveTask() {
        String shareList = "wxsharelist";//redis key值
        Set<String> members = stringRedisTemplate.opsForSet().members(shareList);
        if (null == members || members.size() == 0) {
            return;
        }
        for (String str : members) {
            Map<String, String> ret = (Map) JSON.parse(str);
            String token = ret.get("token");
            String orgId = eventMsgDao.getOrgIdByToken(token);
            ret.put("orgId",orgId);
            Map customerInfo = customerDao.getCustomerByTokenOpenid(ret);
            if (null != customerInfo) {
                // 没有上级且上级不是自己
                if (StringUtils.isEmpty(customerInfo.get("pCustomerId")) && !ret.get("eventkey").equals(customerInfo.get("customerId"))) {
                    String pid = ret.get("eventkey");

                    Map<String, Object> pcustomerInfo = mallBoomService.getCustomerInfoByCustomerId(pid);
                    if (pcustomerInfo != null) {
                        String porgId = pcustomerInfo.get("orgId").toString();
                        if(orgId.equals(porgId)){
                            int customerCountByPidAndId = customerDao.getCustomerCountByPidAndId(pid, customerInfo.get("customerId").toString());
                            if (customerCountByPidAndId < 1) {//若关注用户不是推荐人的上级，保存关系
                                Map<String, String> tmpParam = new HashMap<>();
                                tmpParam.put("orgId", (String) pcustomerInfo.get("orgId"));
                                tmpParam.put("customerId", pid);
                                Integer promoterCount = mallBoomService.getPromoterCount(tmpParam);
                                if (promoterCount > 0) {
                                    //是加盟代理才建立上下级关系
                                    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    ret.put("pSaveTime", date);
                                    ret.put("parentShareWay", "scan");
                                    customerDao.saveCustomerParent(ret);
                                }
                            }
                        }
                    }
                }
                // 换手机号
                String customerId = ret.get("eventkey");
                String phone = customerDao.getSalerPhoneNumberByCid(customerId);
                if (!StringUtils.isEmpty(phone)) {
                    Customer customer = new Customer();
                    customer.setCustomerId(customerId);
                    customer.setCustomerPhone(phone);
                    customerDao.updateByPrimaryKeySelective(customer);
                }
                // 打标签
                String customerId1 = (String) customerInfo.get("customerId");
                String labelIds = customerDao.getLabelIdsBySalerId(customerId);
                if (!StringUtils.isEmpty(labelIds)) {
                    String[] split = labelIds.split(",");
                    Map<String, Object> map = new HashMap<>();
                    map.put("customerId", customerId1);
                    map.put("labelId", split);
                    labelDao.updateLabelsRelation(map);
                }

            }
            stringRedisTemplate.opsForSet().remove(shareList, str);
        }
    }
}
